package org.syndicate.domain;

import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

/**
 * Expresses how to share SharePie.<br/>
 * AmountPie shares a pie by amount.
 * 
 * @author akiraabe
 */
@RooJavaBean
@RooToString
@RooEntity(inheritanceType = "JOINED")
public class AmountPie extends SharePie {
	
	/**
	 * {@inheritDoc}
	 */
	@Transactional
	@Override
	public void create() {
		System.out.println("AmountPie#create");
		Double amount = 0.0;
		for (Share share : getShares()) {
			amount += share.getAmount();
		}
		if (!amount.equals(getAmount())) {
			System.out.println("Not much => " + amount);
		}
		this.setAmount(amount);
		this.setDiscriminator("AmountPie");
	}
	/**
	 * {@inheritDoc}
	 * <br/>
	 * SharePie is shared by amount.
	 */
	@Override
	public SharePie prorate(Double amount) {
		System.out.println("AmountPie#prorate");

		SharePie newSharePie = new AmountPie();
		newSharePie.setAmount(amount);
		newSharePie.setDiscriminator("AmountPie");
		
		Double ratio = amount / this.getAmount();	
		for (Share share : this.getShares()) {
			Share newShare = new Share();
			newShare.setAmount(share.getAmount() * ratio);
			newShare.setOwner(share.getOwner());
			newSharePie.addShare(newShare);
		}
		
		return newSharePie;
	}
	
	/**
	 * Add parameter value to existing SharePie.
	 * 
	 * @param sharePie. Parameter of plus operation.
	 * @return Existing sharePie added by plus operation.
	 */
	public SharePie plus(SharePie sharePie) {
		
		System.out.println("AmountPie#plus");
		
		this.setAmount(this.getAmount() + sharePie.getAmount());
		for (Share share : this.getShares()) {
			for (Share paramShare : sharePie.getShares()) {
				if (share.getOwner() == paramShare.getOwner()) {
					share.setAmount(share.getAmount() + paramShare.getAmount());
				}
			}
		}
		return this;
	}
	
	/**
	 * Subtract parameter value from existing SharePie.
	 * 
	 * @param sharePie. Parameter of minus operation.
	 * @return Existing sharePie subtracted by minus operation.
	 */
	public SharePie minus(SharePie sharePie) {
		
		System.out.println("AmountPie#minus");
		
		this.setAmount(this.getAmount() - sharePie.getAmount());
		for (Share share : this.getShares()) {
			for (Share paramShare : sharePie.getShares()) {
				if (share.getOwner() == paramShare.getOwner()) {
					share.setAmount(share.getAmount() - paramShare.getAmount());
				}
			}
		}
		return this;
	}
}
